package studio.raptor.ddal.demo.jmeter.oracle;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.concurrent.atomic.AtomicLong;
import javax.sql.DataSource;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import studio.raptor.ddal.jdbc.RaptorDataSource;

/**
 * @author Sam
 * @since 3.0.0
 */
public class DdalSelectSampler extends AbstractJavaSamplerClient {

  private static final AtomicLong ID = new AtomicLong(System.currentTimeMillis());
  private static DataSource dataSource;

  private DataSource getDataSource() {
    if (null == dataSource) {
      synchronized (this) {
        if (null == dataSource) {
          dataSource = new RaptorDataSource("school", "oracle");
        }
      }
    }
    return dataSource;
  }

  @Override
  public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
    SampleResult sampleResult = new SampleResult();
    sampleResult.sampleStart();
    try (
        Connection conn = getDataSource().getConnection();
        PreparedStatement statement = conn.prepareStatement(JMeterConstants.INSERT);
    ) {
      statement.setLong(1, ID.getAndIncrement());
      int resultSet = statement.executeUpdate();
      if (resultSet == 1) {
        sampleResult.setSuccessful(true);
      } else {
        sampleResult.setSuccessful(false);
      }
      sampleResult.setSuccessful(true);
      conn.commit();
    } catch (Exception e) {
      e.printStackTrace();
      sampleResult.setSuccessful(false);
    }
    sampleResult.sampleEnd();
    return sampleResult;
  }

}
